import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatSessionDetail } from '@/types/chat';

// 聊天会话详情查询参数
interface ChatSessionDetailParams {
  chatId: string;
}

// POST /api/client/chat/sessions/detail - 获取聊天会话详情
async function handlePost(request: NextRequest): Promise<ChatSessionDetail> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析参数
  const { chatId }: ChatSessionDetailParams = await request.json();

  if (!chatId) {
    throw new Error('聊天会话ID为必填项');
  }

  // 4. 查询聊天会话和消息
  const chatSession = await prisma.chatSession.findFirst({
    where: {
      chatId,
      userId: userId,
    },
    include: {
      messages: {
        orderBy: { createdAt: 'asc' },
        select: {
          id: true,
          chatItemId: true,
          role: true,
          content: true,
          createdAt: true
        }
      }
    }
  });

  if (!chatSession) {
    // 会话不存在，返回新建会话的标识
    return {
      id: '',
      chatId: chatId,
      title: '',
      userId: userId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      messages: [],
      isNewSession: true // 标识这是一个新建会话
    };
  }

  // 5. 数据转换
  return {
    id: chatSession.id,
    chatId: chatSession.chatId,
    title: chatSession.title || '新对话',
    userId: chatSession.userId,
    createdAt: chatSession.createdAt.toISOString(),
    updatedAt: chatSession.updatedAt.toISOString(),
    messages: chatSession.messages.map(msg => ({
      id: msg.id,
      chatItemId: msg.chatItemId,
      chatId: chatSession.chatId,
      role: msg.role,
      content: msg.content,
      createdAt: msg.createdAt.toISOString()
    })),
  };
}

export const POST = withMiddleware(handlePost);
